#include "dispatcher.hh"
#include "serverhandler.hh"
#include <list>
#include <iostream>
#include <string>

using namespace std;

static void loadServers(list<ServerHandler*> *servers, string conf)
{
    FILE *file;
    char buff[1024];
    char *line = buff;
    size_t lineSize;
    int j;
    string address;
    int port;
    ServerHandler *server;

    if (0 == (file = fopen(conf.c_str(), "r")))
    {
        cerr << "Cannot open configuration file" << endl;
        return;
    }

    bzero(line, 1024);
    lineSize = 1024;
    while (getline(&line, &lineSize, file) > 0)
    {
        if (line[0] != '#' && line[0] != '\0' && line[0] != '\n')
        {
            for (j = 0; line[j] != ' ' && line[j] != '\t' && line[j] != '\n' && line[j] != '\0'; ++j);
            address = string(line, j);
            for (; (line[j] == ' ' || line[j] == '\t') && line[j] != '\n' && line[j] != '\0'; ++j);
            port = atoi(line + j);

            cout << "Server found [IP: " << address << " | Port: " << port << "]" << endl;
            server = new ServerHandler(address, port);
            server->Start();
            servers->push_back(server);
        }
        bzero(line, 1024);
        lineSize = 1024;
    }
    fclose(file);
}

int main(int ac, char **av)
{
    char car;
    Dispatcher dispatcher;
    list<ServerHandler*> servers;

    if (ac == 2)
        loadServers(&servers, string(av[1]));
    else if (ac == 4)
        dispatcher = Dispatcher(string(av[3]), atoi(av[4]));
    else
    {
        cerr << "Usage: ./Dispatcher 'servers.conf' ['address' 'port']" << endl;
        return (1);
    }

    if (servers.size() == 0)
    {
        cerr << "No servers to connect to" << endl;
        return (1);
    }

    dispatcher.Start(servers);

    cout << "Press 'q'' or 'ctrl + d' to quit" << endl;
    while (cin >> car)
    {
        if (car == 'q' || car == '\0')
        {
            dispatcher.Stop();
            break;
        }
    }
}
